import http from '../../../services/http/index'
import userStore from '../../../store/user'
import { USER_INFO } from '../../../constants/user'
import { PlainData } from '../../../utils/Data'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    status_renzheng:'' //认证状态

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      'userInfo': Object.assign(
          new PlainData(),
          userStore.getData(USER_INFO),
          { fetching: false }
      )
    });

    if (!userStore.getData(USER_INFO).fetched) {
      this.fetchUserInfo()
    }

    userStore.on('update', () => {
      this.setData({
        userInfo: {
          ...this.data.userInfo,
          ...userStore.getData(USER_INFO)
        }
      });
      console.log(this.data.userInfo)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.setNavigationBarTitle({
      title:'我的主页'
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  // 点击“车主认证”跳转
  gorenzheng: function (e) {
    if (this.data.status_renzheng=='已认证'){
      wx.navigateTo({
        url: '../../my/carOwner/carOwner',
      })
    }else{
      wx.navigateTo({
        url: '../../account/register/step1/RegisterStep1',
      })
    }
  },

  fetchUserInfo() {
    userStore.setData(
      USER_INFO,
      Object.assign(
        new PlainData(),
        userStore.getData(USER_INFO),
        { fetching: true }
      )
    )

    http.getUserInfo()
      .then(data => {
        userStore.setData(
          USER_INFO,
          Object.assign(
            new PlainData(),
            userStore.getData(USER_INFO),
            {
              fetching: false,
              fetched:true,
              data: {
                name: data.info.nickname,
                avatar: data.info.headimg,
                sex: data.info.sex,
                sex_text: data.info.sex_text,
                score: data.comment,
                balance: data.account,
                orders: data.orders,
                status_text: data.status_text
              }
            }
          )
        );
        this.setData({
          status_renzheng: data.status_text
        })
        console.log(this.data.userInfo)
      })
  }
})